import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import * as chat from "../../service/chat";
import io from "socket.io-client";
import { socketUrl } from "@/utils/constant";
const socket = io(socketUrl);

export const fetchChatlist = createAsyncThunk(
  "fetchChatlist",
  async (payload, store) => {
    let dispatch = store.dispatch;
    let state = store.getState();
    try {
      let res = await chat.getMsgList({ _id: state.user._id });

      dispatch(setMsgList({ ...res.data, userid: state.user._id }));
      return res;
    } catch (error) {
      return error;
    }
  }
);
export const fetchReadMsg = createAsyncThunk(
  "fetchReadMsg",
  async (payload, { dispatch, state }) => {
    try {
      let res = await chat.readMsg({ from: payload });
      dispatch(msgRead(payload, res.data));
      return res;
    } catch (error) {
      return error;
    }
  }
);
export const fetchMsgReceive = createAsyncThunk(
  "fetchMsgReceive",
  async (payload, store) => {
    socket.on("receivemsg", (item) => {
      let doc = item._doc;
      const userid = store.getState().user._id;
      store.dispatch(msgRecv({ doc, userid }));
      return { data: "ok" };
    });
  }
);
export const fetchSendMsg = createAsyncThunk(
  "fetchSendMsg",
  async (payload, state) => {
    let { fromUserid: from, toUserid: to, value: msg } = payload;
    socket.emit("sendmsg", { from, to, msg });
    return { data: "ok" };
  }
);

const chatSlice = createSlice({
  name: "chat",
  initialState: {
    chatmsg: [],
    users: {},
    unread: 0,
  },
  reducers: {
    setMsgList(state, { payload }) {
      //payload(chatmsg, users, unread, data, userid)
      state.chatmsg = payload.data;
      state.users = payload.users;
      let unread = payload.data.filter((v) => {
        // to为当前登录用户，并且没有被读
        return !v.read && v.to === payload.userid;
      });
      state.unread = unread.length;
    },
    msgRecv(state, { payload }) {
      // doc(chatmsg),  userid
      // socket获得一个聊天记录， 接收方为当前用户， unread+1
      const n = payload.doc.to === payload.userid ? 1 : 0;
      state.chatmsg = [...state.chatmsg, payload.doc];
      state.unread = state.unread + n;
    },
    // 已读 进入到某人的聊天框，对于某人的信息全变成已读  根据from判断对方是谁
    msgRead(state, { payload }) {
      const { from, num } = payload;
      state.chatmsg = state.chatmsg.map((v) => ({
        ...v,
        read: from === v.from ? true : v.read,
      }));
      state.unread = state.unread - num;
    },
  },
});

export const { setMsgList, msgRecv, msgRead } = chatSlice.actions;
export default chatSlice.reducer;
